package com.ls.rabbitmqService.utils;

import com.ls.baseService.utils.Constants;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ConnectionFactoryUtil {

    static ConnectionFactory factory = new ConnectionFactory();
    static{
        factory.setUsername(Constants.rabbitmqConfig.getUsername());
        factory.setPassword(Constants.rabbitmqConfig.getPassword());
        factory.setVirtualHost(Constants.rabbitmqConfig.getVirtualHost());
        factory.setHost(Constants.rabbitmqConfig.getHost());
        factory.setPort(Constants.rabbitmqConfig.getPort());
    }
    public static Connection getRabbitConnection() {
        Connection conn = null;
        try {
            conn = factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    public static Connection getRabbitConnection2() {
        ConnectionFactory factory = new ConnectionFactory();
        // 连接格式：amqp://userName:password@hostName:portNumber/virtualHost
        String uri = String.format("amqp://%s:%s@%s:%d%s", Constants.rabbitmqConfig.getUsername(), Constants.rabbitmqConfig.getPassword(),
                Constants.rabbitmqConfig.getHost(), Constants.rabbitmqConfig.getPort(),
                Constants.rabbitmqConfig.getVirtualHost());
        Connection conn = null;
        try {
            factory.setUri(uri);
            //virtualHost 虚拟机 类是一个小型的rabbitmq 有自己的交换器，队列等
            factory.setVirtualHost(Constants.rabbitmqConfig.getVirtualHost());
            conn = factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }



}
